package grsu.epam.airline.action;

import grsu.epam.airline.form.LoginForm;
import grsu.epam.airline.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

public class LoginAction extends Action {
	private static final Logger logger = Logger.getLogger(LoginAction.class);

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String target = ForwardActionTo.ERROR;
		LoginForm loginForm = (LoginForm) form;
		UserService userService = new UserService();
		if (userService.getUser(loginForm.getUserName(),
				loginForm.getPassword()) != null) {
			target = ForwardActionTo.SUCCESS;
			request.setAttribute("message", loginForm.getUserName());
			HttpSession session = request.getSession(true);
			session.setAttribute(
					"auth",
					userService.getUser(loginForm.getUserName(),
							loginForm.getPassword()));
			logger.info("Log in...");
		} else {
			ActionMessages errors = new ActionMessages();
			errors.add("invalidUserName", new ActionMessage("error.login.fail",
					loginForm.getUserName()));
			saveErrors(request, errors);
			logger.error("Login or password are incorrect!");
		}
		return mapping.findForward(target);
	}
}